package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/valyala/fasthttp"
	"go.getaway.adminspro.padmins.com/bootstrap"
	"go.getaway.adminspro.padmins.com/untils"
	"go.getaway.adminspro.padmins.com/untils/auth"
	"go.getaway.adminspro.padmins.com/untils/businessCommonQuery"
	"go.getaway.adminspro.padmins.com/untils/config"
	"go.getaway.adminspro.padmins.com/untils/db"
	"go.getaway.adminspro.padmins.com/untils/handler"
	"go.getaway.adminspro.padmins.com/untils/request"
	"go.getaway.adminspro.padmins.com/untils/response"
	"time"
)

func main() {
	Di := bootstrap.Run()
	c := Di.Get("config").(*config.Config)
	fasthttp.ListenAndServe(c.Get("http.addr"), func(ctx *fasthttp.RequestCtx) {
		start := time.Now()
		ctx.Response.Header.Set("Access-Control-Allow-Origin", "*")
		ctx.Response.Header.Set("Access-Control-Allow-methods", "POST, PUT, GET, OPTIONS, DELETE")
		ctx.Response.Header.Set("Access-Control-Allow-Credentials", "true")
		ctx.Response.Header.Set("Access-Control-Allow-Headers", "X-Requested-With,X_Requested_With,Authorization,Content-Type,token,Access-Token")
		if ctx.Request.Header.IsOptions() {
			return
		}
		ctx.Conn().RemoteAddr()
		Request := request.NewFastHttpRequest(ctx)
		Db := db.NewDb(Di.Get("dbConnect").(*db.DbConnect))
		c := &handler.Handler{
			Di:                  Di,
			Db:                  Db,
			Response:            response.NewFastHttpResponse(&ctx.Response),
			Request:             Request,
			Auth:                &auth.Auth{Di: Di, Db: Db},
			BusinessCommonQuery: &businessCommonQuery.BusinessCommonQuery{Di: Di, Request: Request},
		}
		resp := Di.Get("response").(*response.Response)
		method := c.Request.Params("method", "").(string)
		var m *response.Message
		if method == "" {
			m = resp.Error(10000, "method 参数不能为空")
		} else {
			routers := Di.Get("routers").(map[string]func(c *handler.Handler) (map[string]interface{}, untils.Error))
			if router, ok := routers[method]; ok {
				_, e := bootstrap.Permission(c)
				if e != nil {
					m = resp.Error(e.GetCode(), fmt.Sprintf("%v", e))
				} else {
					data, e := router(c)
					if e != nil {
						app_debug := Di.Get("config").(*config.Config).Get("app.debug")
						if app_debug == "1" {
							m = resp.Error(e.GetCode(), fmt.Sprintf("%v", e), e.Error())
						} else {
							m = resp.Error(e.GetCode(), fmt.Sprintf("%v", e))
						}
					} else {
						m = resp.Success(data)
					}
				}
			} else {
				m = resp.Error(10001, fmt.Sprintf("[%s]method 不存在", method))
			}
		}
		m.Runtime = fmt.Sprintf("%v", time.Since(start))
		ctx.Response.Header.Set("Content-Type", "application/json;charset=utf-8")
		res := bytes.NewBuffer([]byte{})
		jsonEncoder := json.NewEncoder(res)
		jsonEncoder.SetEscapeHTML(false)
		e := jsonEncoder.Encode(m)

		if e != nil {
			fmt.Fprint(ctx, e)
		} else {
			fmt.Fprint(ctx, res)
		}
	})
}
